<script setup lang="ts">
import { reactive, ref, onUnmounted } from 'vue';
import { useAddrStore, useAuthStore } from '@/store';
import { useNurseUser, use_hospital_dept_bed } from '@/service';
import Taro, { showToast, showLoading, hideLoading, getCurrentInstance, login } from '@tarojs/taro';
import { SUCCESS_MSG_DURATION } from '@/constants';
import { useGetAuthInfo } from '@/hooks';
import { storeToRefs } from 'pinia';
import ren from '@/assets/img/ren.png'
// import { localStg } from '@/utils';
// import { useImage } from '@/hooks';
// const { imageUrl } = useNurseStore()

const {
    router: {
        params: { type }
    }
}: any = getCurrentInstance();

const { getHospitalList } = use_hospital_dept_bed();

// definePageConfig({
//     navigationBarTitleText: '个人信息'
// });
Taro.setNavigationBarTitle({
    title: type == 1 ? '个人信息设置' : '个人信息新增'
});

onUnmounted(() => useGetAuthInfo());

const { edit, WeChatPhoneNumberDecrypter } = useNurseUser();

const { getProvince, getCity, getCountry } = useAddrStore();

const { nurseUser } = storeToRefs(useAuthStore());

const formData = ref<any>(nurseUser);
// formData.value

const ruleForm = ref<any>(null);

const select = reactive({ text: '', value: '' });

// const token = localStg.get('token');

const submit = async () => {
    // 如果用户已认证，不允许提交
    // if (formData.value.isVerify == '1') {
    //     showToast({
    //         title: '信息已认证，无法修改',
    //         icon: 'none',
    //         duration: 2000
    //     });
    //     return;
    // }

    // const { valid } = await ruleForm.value.validate();

    // if (!valid) return;

    showLoading({ title: '正在保存...' });
    const { error } = await edit({ ...formData.value });
    hideLoading();
    if (!error) {
        showToast({
            title: '保存成功',
            icon: 'success',
            duration: SUCCESS_MSG_DURATION
        });
    }
};
// const headers = ref({
//     'Content-Type': 'multipart/form-data',
//     'X-Access-Token': token
// })

// function uploadDelete() {
//     formData.value.avatar = undefined
// }

// function uploadSuccess({ data }: any) {

//     const result = JSON.parse(data.data)

//     const { message, success } = result

//     if (success && message) formData.value.avatar = message

// }
const areaModule: any = reactive({
    show: false,
    province: getProvince,
    city: [{}],
    country: [{}],
    town: [],
    showArea: () => {
        areaModule.show = !areaModule.show;
        if (areaModule.show) {
            select.text = '';
            select.value = '';
        }
    },
    onChange: (item: any) => {
        const { custom, next, value } = item;

        switch (custom) {
            case 'province':
                const city = getCity.filter(item => item.pid == value.id);
                areaModule.city = city;
                break;
            case 'city':
                const country = getCountry.filter(item => item.pid == value.id);
                areaModule.country = country;
                break;
            default:
                break;
        }
        select.text += value.name;
        select.value += `${value.id}-`;
        const name = areaModule[next];

        if (!name?.length) {
            areaModule.show = false;
            formData.value.areaName = select.text;
            formData.value.area = select.value;
        }
    }
});

const hospitalModule = reactive({
    show: false,
    showHospital: () => {
        hospitalModule.show = !hospitalModule.show;
        if (hospitalModule.show) {
            formData.value.defaultHospital = '';
            formData.value.defaultHospitalName = '';
        }
    },
    onChange: (items: any) => {
        if (items.length == 0) return;
        const item = items[items.length - 1];
        formData.value.defaultHospital = item.key;
        formData.value.defaultHospitalName = item.title;
    },
    lazyLoad: async (pid: string) => {
        const { error, success } = await getHospitalList(pid);
        if (!error && success?.length > 0) {
            const list = success?.map((item: any) => {
                return {
                    value: item,
                    text: item.title
                };
            });
            return list;
        }
        return [];
    }
});

const onChooseAvatar = (e: any) => {
    // onChooseAvatar
    formData.value.avatar =  e.detail.avatarUrl;
    // http://tmp/IxcPpQ4fe8a045e790b3d5cbdc519aa573a9196c3ef8.jpeg
    uploadAvatar(e.detail.avatarUrl);
   
} 

function uploadAvatar(filePath: string) {
    Taro.uploadFile({
        // url: 'https://anfine.huasun-healthcare.com:80/api/registOrder/updateRgstPhotos', // 替换为你的后端接口地址
        // url: 'http://127.0.0.1:8082/file-service/FileUpload/saveImage', // 替换为你的后端接口地址
        url: 'https://anfine.huasun-healthcare.com:80/file-service/FileUpload/custom_saveImage', // 替换为你的后端接口地址
        filePath: filePath,
        name: 'file', // 后端接收文件的字段名
        formData: {
          // 如果需要额外的表单数据，可以在这里添加
        //   'orderId': orderId,
        //   'type': type, //表单1级菜单序号，0表示无
        //   'childrenIndex': childrenIndex, //2级菜单序号，0表示无
        //   'fileType': fileType
        },
        success: (uploadRes) => {
          // 上传成功
          // 处理上传成功后的逻辑
        //   uploadAvatar(uploadRes.data);
          formData.value.avatar = uploadRes.data;
        },
        fail: (err) => {
          // 上传失败
          // 处理上传失败的逻辑
        }
    });
}

// 处理微信授权获取手机号
const handlePhoneAuth = async (e: any) => {
    // 如果用户已认证，不允许修改
    // if (formData.value.isVerify == '1') {
    //     showToast({
    //         title: '信息已认证，无法修改',
    //         icon: 'none',
    //         duration: 2000
    //     });
    //     return;
    // }

    const data = {
        code: '',
        encryptedData: e.detail.encryptedData,
        iv: e.detail.iv,
    };

    if (e.detail.errMsg === 'getPhoneNumber:ok') {
        showLoading({ title: '正在获取手机号...' });
        try {
            // 获取 code
            const res = await login();
            data.code = res.code;

            // 调用解密接口
            const { error, success } = await WeChatPhoneNumberDecrypter(data);
            console.log("success", success);
            hideLoading();
            
            if (!error && success) {
                formData.value.phone = success;
                showToast({
                    title: '获取手机号成功',
                    icon: 'success',
                    duration: SUCCESS_MSG_DURATION
                });
            } else {
                showToast({
                    title: '获取手机号失败',
                    icon: 'none',
                    duration: 2000
                });
            }
        } catch (err) {
            hideLoading();
            showToast({
                title: '获取手机号失败',
                icon: 'none',
                duration: 2000
            });
        }
    } else {
        // 用户拒绝授权
        showToast({
            title: '用户拒绝授权手机号码',
            icon: 'none',
            duration: 2000
        });
    }
};


</script>
<template>
    <basic-layout>
        <!-- <custom-navbar :title="type == 1 ? '个人信息设置' : '个人信息新增'" showLeft /> -->
        <view class="w-375px flex-col-center bg-gray-100 min-h-screen">
            <view class="w-360px py-[20rpx]">
                <nut-form ref="ruleForm" class="w-full" :model-value="formData">
                    <!-- 头像选择区域 -->
                    <view class="w-full flex-center py-[40rpx] mb-[20rpx] bg-gray-50 rounded-[16rpx]">
                        <view class="flex-col-center">
                            <button 
                                class="relative mb-[16rpx]"
                                open-type="chooseAvatar" 
                                @chooseavatar="onChooseAvatar"
                            >
                                <image 
                                    class="w-[120rpx] h-[120rpx] rounded-[60rpx] border-[4rpx] border-white shadow-lg"
                                    :src="formData.avatar || ren" 
                                    mode="aspectFill"
                                ></image>
                                <view class="absolute bottom-0 right-0 w-[36rpx] h-[36rpx] bg-blue-500 rounded-[18rpx] flex-center shadow-md">
                                    <text class="text-white text-[24rpx] font-bold">+</text>
                                </view>
                            </button>
                           
                            <text class="text-[28rpx] text-gray-600">{{ '点击更换头像' }}</text>
                        </view>
                    </view>

                    <!-- 基本信息区域 -->
                    <view class="w-full bg-white box-border rounded-[16rpx] p-[24rpx] mb-[20rpx] shadow-sm">
                        <view class="flex justify-between items-center mb-[24rpx]">
                            <text class="text-[32rpx] font-bold text-gray-800">基本信息</text>
                            <text v-if="formData.isVerify == '1'" class="text-[24rpx] text-green-600 bg-green-100 px-[12rpx] py-[4rpx] rounded-[8rpx]">已认证</text>
                        </view>
                        
                        <nut-form-item label="姓名" prop="name">
                            <nut-input 
                                class="bg-gray-50 rounded-[12rpx] px-[16rpx] py-[12rpx]"
                                :readonly="formData.isVerify == '1'"
                                :disabled="formData.isVerify == '1'"
                                v-model="formData.name" 
                                placeholder="请输入姓名" 
                                type="text" 
                            />
                        </nut-form-item>

                        <nut-form-item label="联系电话" prop="phone">
                            <view class="flex items-center gap-[12rpx]">
                                <!-- <nut-input 
                                    v-if="formData.isVerify == '10'"
                                    class="flex-1 bg-gray-50 rounded-[12rpx] px-[16rpx] py-[12rpx]"
                                    :readonly="true"
                                    :disabled="true"
                                    v-model="formData.phone" 
                                    placeholder="请通过微信授权获取手机号" 
                                    type="text" 
                                /> -->
                                <button 
                                    v-if="formData.isVerify != '1'"
                                    open-type="getPhoneNumber" 
                                    @getphonenumber="handlePhoneAuth"
                                    class="flex items-center justify-center px-[24rpx] h-[64rpx] rounded-[12rpx] bg-white text-gray-700 text-[28rpx] border border-gray-300"
                                >
                                    {{  formData.phone || '获取手机号' }}
                                </button>
                                <view v-else class="flex items-center justify-center px-[24rpx] h-[64rpx] rounded-[12rpx] bg-gray-50 text-gray-500 text-[28rpx] border border-gray-200">
                                    {{ formData.phone || '暂无手机号' }}
                                </view>
                            </view>
                        </nut-form-item>

                        <nut-form-item label="身份证" prop="idcard">
                            <nut-input 
                                class="bg-gray-50 rounded-[12rpx] px-[16rpx] py-[12rpx]"
                                :readonly="formData.isVerify == '1'"
                                :disabled="formData.isVerify == '1'"
                                v-model="formData.idcard" 
                                placeholder="请输入身份证号" 
                                type="text" 
                            />
                        </nut-form-item>
                    </view>
                    <!-- <nut-form-item class=" flex-center" label="头像" prop="name"
                        :rules="[{ required: false, message: '' }]">
                        <nut-uploader :multiple="false" @success="uploadSuccess" @delete="uploadDelete"
                            :headers="headers" :maximize="1024 * 2000" :url="`${imageUrl}/upload?biz=weapp`"
                            maximum="1">
                            <template #default>
                                <nut-avatar size="large">
                                    <img v-if="nurseUser.avatar" :src="useImage(nurseUser.avatar)" />
                                    <view v-else class=" m-t-2 w-90 h-90 bg-primary i-local-default_img" />
                                </nut-avatar></template>
</nut-uploader>
</nut-form-item> -->
                    <!-- 其他信息区域 -->
                    <view class="w-full bg-white rounded-[16rpx] p-[24rpx] mb-[20rpx] shadow-sm">
                        <text class="text-[32rpx] font-bold text-gray-800 mb-[24rpx] block">其他信息</text>
                        
                        <nut-form-item label="性别" prop="sex" :rules="[{ required: false, message: '请选择性别' }]">
                            <NutRadioGroup v-model="formData.sex" direction="horizontal">
                                <nut-radio :disabled="formData.isVerify == '1'" label="1">男</nut-radio>
                                <nut-radio :disabled="formData.isVerify == '1'" label="2">女</nut-radio>
                            </NutRadioGroup>
                        </nut-form-item>
                        
                        <!-- <nut-form-item label="地区" prop="areaName">
                            <nut-input 
                                class="bg-gray-50 rounded-[12rpx] px-[16rpx] py-[12rpx]"
                                v-model="formData.areaName" 
                                placeholder="请选择地区" 
                                type="text"
                                @click="formData.isVerify != '1' ? areaModule.showArea() : null" 
                            />
                            <nut-address v-model:visible="areaModule.show" :province="areaModule.province"
                                :city="areaModule.city" :country="areaModule.country" :town="areaModule.town"
                                custom-address-title="请选择所在地区" @change="areaModule.onChange"></nut-address>
                        </nut-form-item>
                        
                        <nut-form-item label="详细地址" prop="address">
                            <nut-input 
                                class="bg-gray-50 rounded-[12rpx] px-[16rpx] py-[12rpx]"
                                v-model="formData.address" 
                                placeholder="请输入详细地址" 
                                type="text" 
                            />
                        </nut-form-item> -->

                        <nut-form-item label="默认医院" prop="defaultHospitalName" :rules="[{ required: false, message: '' }]">
                            <nut-input 
                                class="bg-gray-50 rounded-[12rpx] px-[16rpx] py-[12rpx]"
                                v-model="formData.defaultHospitalName" 
                                placeholder="请选择默认医院" 
                                type="text"
                                @click="formData.isVerify != '1' ? hospitalModule.showHospital() : null" 
                            />
                            <basic-hospital v-model:visible="hospitalModule.show" :lazy-load="hospitalModule.lazyLoad"
                                :title="formData.defaultHospitalName" @change="hospitalModule.onChange" />
                        </nut-form-item>
                    </view>

                    <!-- 保存按钮区域 -->
                    <view class="w-full flex-center py-[40rpx]">
                        <basic-button 
                            :text="'保存信息'" 
                            class="w-[300rpx] h-[80rpx]" 
                            @on-click="submit" 
                        />
                    </view>
                </nut-form>
            </view>
        </view>
    </basic-layout>
</template>


